package com.gxa.hualian.service.impl;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.gxa.hualian.controller.ExceptionController;
import com.gxa.hualian.exception.BusinessException;
import com.gxa.hualian.mapper.TicketMapper;
import com.gxa.hualian.pojo.Ticket;
import com.gxa.hualian.service.TicketService;
import com.gxa.hualian.util.JsonResult;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Author 杨天可
 * @Date 2020/10/20 15:48
 * @Version 1.0
 */
@Service("ticketService")
public class TicketServcieImpl implements TicketService {

    @Resource
    TicketMapper ticketMapper;


    @Override
    public int add(Ticket ticket) {

        //设置优惠券的默认状态  0：未领取   1：已领取
        ticket.setState(0);
        JsonResult jsonResult = new JsonResult();
        if (ticket.getName().equals("") || ticket.getDesc().equals("") || ticket.getRole().equals("") ||
                ticket.getCollectExpired().toString().equals("") || ticket.getUseExpired().toString().equals("") || ticket.getState()==null
                || ticket.getImg().equals("")){
            throw new BusinessException("请完善优惠券信息");
        }

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(ticket.getCollectExpired());
        calendar.add(Calendar.DATE,3);
        if(ticket.getCollectExpired().after(ticket.getUseExpired())){
            throw new BusinessException("优惠券至少在使用截止日期前三天领取");
        }else {
            int insert = ticketMapper.insert(ticket);
            jsonResult.setCode("200");
            jsonResult.setMsg("添加成功");
            return insert;
        }
    }

    @Override
    public Ticket getTktById(Integer id) {
        Ticket ticket = ticketMapper.selectByPrimaryKey(id);
        return ticket;
    }

    @Override
    public List<Ticket>  getTktList() {
        List<Ticket> tickets = ticketMapper.selectAll();
        return tickets;
    }

    @Override
    public Map updateState(Integer id, Integer state) {

        Ticket ticket = new Ticket();
        ticket.setId(id);
        ticket.setState(state);
        int i = ticketMapper.updateByPrimaryKeySelective(ticket);
        JsonResult jsonResult = new JsonResult();
        if(i != 0 ){
            jsonResult.setCode("200");
            jsonResult.setMsg("修改成功");
        }else {
            throw new BusinessException("发生未知错误");
        }
        return jsonResult.getValues();
    }
}
